package com.hele.sts.action;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.hele.sts.dao.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.hele.sts.pub.Constants;
import com.hele.sts.pub.CxqxUtil;
import com.hele.sts.pub.StringUtil;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import org.springframework.beans.factory.annotation.Autowired;

public class PrintAction implements Action{
	private static final Logger logger = LoggerFactory.getLogger(PrintAction.class);
	
	private String id;
	private String filePath;
	private String sfdy;

    /** 打印页数 */
    private int dyys;
    private String msg;
	private String batch;
	private String userId;
	private XtServer xtServer;
	private List<Wjxx> wjxxList;  
	private String inmlbhs;

	@Autowired
	private XtLogDao xtLogDao;

	@Override
	public String execute(){
        ActionContext ctx = ActionContext.getContext();
        Map session = ctx.getSession();
        userId = (String) session.get("userid");
        String username = (String)session.get("user_name");
		//batch print page
		if("1".equals(batch)){

			if (StringUtils.isBlank(userId)) {
				return "login";
			}
			String[] strs = id.split("_");
			if (strs.length != 3) {
				throw new IllegalArgumentException();
			}
			String nbxh = strs[0], zfjbz=strs[1],jnmlbh = strs[2];
			//log query
			addLog(userId,nbxh);
			return "batch";
		}else if("2".equals(batch)){
			//return the ftp info and file path to the client
			String[] strs = id.split("_");
			if (strs.length != 3) {
				throw new IllegalArgumentException();
			}
			String nbxh = strs[0], zfjbz=strs[1],jnmlbh = strs[2];
			xtServer = XtServerDao.getServerForJnml(nbxh,zfjbz,jnmlbh);
			wjxxList = QyjnmlbDao.getWjxxList(nbxh, jnmlbh);
			//filter by cxqx
			String cxqx = (String)session.get("cxqx");
			if(cxqx==null) {
                cxqx = Constants.USER_CXQX_WY;
            }
			wjxxList = Lists.newArrayList(Collections2.filter(wjxxList, filterIt(cxqx)));
			return "jsonp";
		}
			
		if ("1".equals(sfdy)) {
			
			if(userId==null){
				msg = "error";
				return "jsonp";
			}
//			ActionContext ctx = ActionContext.getContext();
//			Map session = ctx.getSession();
//			String userId = (String) session.get("userid");
//			if ((userId == null) || ("".equals(userId))) {
//				msg = "error";
//				return "jsonp";
//			}
			String[] strs = id.split("_");
			if (strs.length != 4) {
				msg = "error";
				return "jsonp";
			}
			String nbxh = strs[0], jnmlbh = strs[1], inmlbh = strs[2], djjg = strs[3];
			if (StringUtils.isBlank(nbxh) || StringUtils.isBlank(jnmlbh) || StringUtils.isBlank(inmlbh)) {
				msg = "error";
				return "jsonp";
			}
			logger.debug("dy it");
			dy(userId, nbxh, Integer.valueOf(jnmlbh), Integer.valueOf(inmlbh), dyys);
			msg="success";
			xtLogDao.insertLog("业务日志","打印企业档案",userId,username,"成功","用户："+userId+" 打印企业："+nbxh+" 档案信息，卷内目录编号："+jnmlbh+" 件内目录编号:"+inmlbh,this.getClass().getName());

			return "jsonp";
		}
		else if("2".equals(sfdy)){ //批量打印回写日志
			if(userId==null){
				msg = "error";
				return "jsonp";
			}
			String[] strs = id.split("_");
			if (strs.length != 3) {
				msg = "error";
				return "jsonp";
			}
			String nbxh = strs[0], zfjbz = strs[1], jnmlbh = strs[2];
			if (StringUtils.isBlank(nbxh) || StringUtils.isBlank(zfjbz) || StringUtils.isBlank(jnmlbh)) {
				msg = "error";
				return "jsonp";
			}
			
			batchDy(userId,nbxh,Integer.valueOf(jnmlbh),inmlbhs);
            xtLogDao.insertLog("业务日志","批量打印企业档案",userId,username,"成功","用户："+userId+" 批量打印企业："+nbxh+" 档案信息，卷内目录编号：",this.getClass().getName());

        }
		return "success";
		
	}

	private void batchDy(String userId, String nbxh, Integer jnmlbh, String inmlbhs) {
		List<Map> inmlbhList = JSON.parseArray(inmlbhs, Map.class);
		for (Map map : inmlbhList) {
			int inmlbh = (Integer)map.get("inmlbh");
			int dyys = (Integer)map.get("pages");
			dy(userId,nbxh,jnmlbh,inmlbh,dyys);
		}
		
	}

	private void dy(String userId, String nbxh, int jnmlbh, int inmlbh, int dyys) {
		QUser qUser = QUserDao.load(userId);
		QPrintLog log = QPrintLogDao.query(userId, nbxh, qUser.getDjid(), jnmlbh, inmlbh);
			log = new QPrintLog();
			log.setLogId(StringUtil.createLogId());
			log.setUserId(userId);
			log.setNbxh(nbxh);

			log.setDjid(qUser.getDjid());
			log.setJnmlbh(jnmlbh);
			log.setInmlbh(inmlbh);
			log.setSfdy("1");
			log.setDays(dyys);
			QPrintLogDao.insert(log);
	}
	
	private void addLog(String userId, String nbxh) {
		QUser quser = QUserDao.load(userId);
		QEkUser bean = QEkUserDao.load(userId);
		Qyhznr qyhznr = QyhznrDao.load(nbxh);
		if (qyhznr == null) {
			qyhznr = QyhznrDao.loadBfTj(nbxh);
		}
		if (qyhznr == null) {
			logger.error("保存日志失败,未获取到企业信息");
			return;
		}
		Qyajb qyajb = QyajbDao.load(nbxh);
		QLog qLog = createrQLog2(qyhznr, quser, bean, qyajb);
		if (!QLogDao.insert(qLog)) {
			logger.error("保存日志失败");
			return;
		}
	}
	
	QLog createrQLog2(Qyhznr qyhznr, QUser qUser, QEkUser bean, Qyajb qyajb) {
		QLog log = new QLog();
		logger.debug(qUser.getCxrq() + "." + StringUtil.createLogId() + "." + qyhznr.getNbxh() + "."
				+ qyhznr.getQymc().trim() + "." + qUser.getUserId() + "." + qUser.getYhlx());
		logger.debug(qUser.getUserName() + "." + bean.getUserName() + "." + qyhznr.getZch());

		log.setCxrq(new Date());
		log.setLogId(StringUtil.createLogId());
		log.setNbxh(qyhznr.getNbxh().trim());
		log.setQymc(qyhznr.getQymc().trim());
		log.setUserId(qUser.getUserId().trim());
		log.setUserName(qUser.getUserName().trim());
		log.setUserNameEk(bean.getUserName().trim());
		log.setYhlx(qUser.getYhlx().trim());
		log.setZch(qyhznr.getZch().trim());

		log.setRealName(qUser.getRealName());
		log.setYhsf(qUser.getYhsf());
		log.setBz(qUser.getBz());
		log.setDyfs(qUser.getDyfs());
		// xuning add 20150101
		log.setCxmd(qUser.getCxmd());
		// xuning add 20150113
		log.setDjid(qUser.getDjid());
		if (qyajb != null ) {
			int days = qyajb.getJnys();
			log.setDays(days);
		}
		log.setSfdy("0");
		return log;
	}
	/**
	 * @return the id
	 */
	public String getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(String id) {
		this.id = id;
	}

	/**
	 * @return the filePath
	 */
	public String getFilePath() {
		return filePath;
	}

	/**
	 * @param filePath the filePath to set
	 */
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	/**
	 * @return the sfdy
	 */
	public String getSfdy() {
		return sfdy;
	}

	/**
	 * @param sfdy the sfdy to set
	 */
	public void setSfdy(String sfdy) {
		this.sfdy = sfdy;
	}

	/**
	 * @return the dyys
	 */
	public int getDyys() {
		return dyys;
	}

	/**
	 * @param dyys the dyys to set
	 */
	public void setDyys(int dyys) {
		this.dyys = dyys;
	}

	/**
	 * @return the msg
	 */
	public String getMsg() {
		return msg;
	}

	/**
	 * @param msg the msg to set
	 */
	public void setMsg(String msg) {
		this.msg = msg;
	}

	/**
	 * @return the batch
	 */
	public String getBatch() {
		return batch;
	}

	/**
	 * @param batch the batch to set
	 */
	public void setBatch(String batch) {
		this.batch = batch;
	}

	/**
	 * @return the userId
	 */
	public String getUserId() {
		return userId;
	}

	/**
	 * @param userId the userId to set
	 */
	public void setUserId(String userId) {
		this.userId = userId;
	}

	/**
	 * @return the xtServer
	 */
	public XtServer getXtServer() {
		return xtServer;
	}

	/**
	 * @param xtServer the xtServer to set
	 */
	public void setXtServer(XtServer xtServer) {
		this.xtServer = xtServer;
	}

	/**
	 * @return the wjljmcList
	 */
	public List<Wjxx> getWjxxList() {
		return wjxxList;
	}

	/**
	 * @param wjxxList the wjljmcList to set
	 */
	public void setWjxxList(List<Wjxx> wjxxList) {
		this.wjxxList = wjxxList;
	}

	/**
	 * @return the inmlbhs
	 */
	public String getInmlbhs() {
		return inmlbhs;
	}

	/**
	 * @param inmlbhs the inmlbhs to set
	 */
	public void setInmlbhs(String inmlbhs) {
		this.inmlbhs = inmlbhs;
	}
	
	private Predicate<Wjxx> filterIt(final String cxqx) {
		return new Predicate<Wjxx>() {

			@Override
			public boolean apply(Wjxx input) {
				boolean res =  CxqxUtil.highCxqx(input.getCxqx(),cxqx);
				return res;
			}
		};
	}
	
}
